package com.xy.xyaicpzs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xy.xyaicpzs.common.DeleteRequest;
import com.xy.xyaicpzs.common.ErrorCode;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.common.requset.VipCodeActivateRequest;
import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.domain.dto.user.*;
import com.xy.xyaicpzs.domain.entity.User;
import com.xy.xyaicpzs.domain.vo.*;
import com.xy.xyaicpzs.exception.BusinessException;
import com.xy.xyaicpzs.service.UserService;
import com.xy.xyaicpzs.service.VipCodeService;
import com.xy.xyaicpzs.service.SmsService;
import com.xy.xyaicpzs.util.UserAuthValidator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户接口
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController {

    @Resource
    private UserService userService;
    
    @Resource
    private VipCodeService vipCodeService;
    
    @Resource
    private SmsService smsService;
    
    @Resource
    private UserAuthValidator userAuthValidator;

    // region 登录相关

    /**
     * 用户登录
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public ApiResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @Operation(summary = "用户注销", description = "用户注销接口")
    public ApiResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @Operation(summary = "获取当前登录用户", description = "获取当前登录用户信息")
    public ApiResponse<UserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @Operation(summary = "创建用户", description = "管理员创建用户")
    public ApiResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        // 验证超级管理员权限
        ApiResponse<Long> authResult = userAuthValidator.validateSuperAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 参数校验
        String userAccount = userAddRequest.getUserAccount();
        String userPassword = userAddRequest.getUserPassword();
        String password = userAddRequest.getPassword();
        String phone = userAddRequest.getPhone();
        
        // 如果userPassword为空但password不为空，则使用password
        if (StringUtils.isBlank(userPassword) && StringUtils.isNotBlank(password)) {
            userAddRequest.setUserPassword(password);
            userPassword = password;
        }
        
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码不能为空");
        }
        
        if (phone != null && !phone.isEmpty()) {
            // 如果提供了手机号，可以进行手机号格式校验
            if (phone.length() != 11) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
            }
        }
        
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        
        // 密码加密，使用Service层的加密方法
        String encryptPassword = userService.encryptPassword(userPassword);
        user.setUserPassword(encryptPassword);
        
        boolean result = userService.save(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return ResultUtils.success(user.getId());
    }

    /**
     * 修改用户状态
     *
     * @param userStatusUpdateRequest 用户状态更新请求
     * @param request HTTP请求
     * @return 修改结果
     */
    @PostMapping("/update-status")
    @Operation(summary = "修改用户状态", description = "管理员修改用户状态（正常/封禁）")
    public ApiResponse<Boolean> updateUserStatus(@RequestBody UserStatusUpdateRequest userStatusUpdateRequest, 
                                                HttpServletRequest request) {
        // 验证超级管理员权限
        ApiResponse<Boolean> authResult = userAuthValidator.validateSuperAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (userStatusUpdateRequest == null || userStatusUpdateRequest.getId() == null 
                || userStatusUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不正确");
        }
        
        Long id = userStatusUpdateRequest.getId();
        Integer status = userStatusUpdateRequest.getStatus();
        
        // 校验状态值
        if (status == null || (status != 0 && status != 1)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "状态值不正确，应为0(正常)或1(封禁)");
        }
        
        // 检查目标用户是否存在
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        
        // 更新用户状态
        user.setStatus(status);
        boolean result = userService.updateById(user);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作失败");
        }
        
        return ResultUtils.success(true);
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @Operation(summary = "删除用户", description = "管理员删除用户")
    public ApiResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        // 验证超级管理员权限
        ApiResponse<Boolean> authResult = userAuthValidator.validateSuperAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public ApiResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request) {
        // 验证登录权限
        ApiResponse<Boolean> authResult = userAuthValidator.validateLoginAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 获取当前登录用户
        User currentUser = userAuthValidator.getCurrentUser(request);
        Long targetUserId = userUpdateRequest.getId();
        
        // 权限检查：用户只能修改自己的信息，管理员可以修改任何用户
        if (!currentUser.getId().equals(targetUserId) && !userAuthValidator.isAdmin(currentUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限修改其他用户信息");
        }
        
        // 参数校验
        String userPassword = userUpdateRequest.getUserPassword();
        String password = userUpdateRequest.getPassword();
        String phone = userUpdateRequest.getPhone();
        
        // 如果userPassword为空但password不为空，则使用password
        if (StringUtils.isBlank(userPassword) && StringUtils.isNotBlank(password)) {
            userUpdateRequest.setUserPassword(password);
            userPassword = password;
        }
        
        if (phone != null && !phone.isEmpty()) {
            // 如果提供了手机号，可以进行手机号格式校验
            if (phone.length() != 11) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
            }
        }
        
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        
        // 如果更新了密码，需要进行加密
        if (StringUtils.isNotBlank(userPassword)) {
            String encryptPassword = userService.encryptPassword(userPassword);
            user.setUserPassword(encryptPassword);
        }
        
        boolean result = userService.updateById(user);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户信息")
    public ApiResponse<UserVO> getUserById(@RequestParam("id") long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "获取用户列表", description = "获取用户列表，支持用户名/手机号模糊匹配和角色状态筛选")
    public ApiResponse<List<UserVO>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        if (userQueryRequest != null) {
            // 用户名模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getUserName())) {
                queryWrapper.like("userName", userQueryRequest.getUserName());
            }
            
            // 手机号模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getPhone())) {
                queryWrapper.like("phone", userQueryRequest.getPhone());
            }
            
            // 账号模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getUserAccount())) {
                queryWrapper.like("userAccount", userQueryRequest.getUserAccount());
            }
            
            // 用户角色精确匹配
            if (userQueryRequest.getUserRole() != null) {
                queryWrapper.eq("userRole", userQueryRequest.getUserRole());
            }
            
            // 用户状态精确匹配
            if (userQueryRequest.getStatus() != null) {
                queryWrapper.eq("status", userQueryRequest.getStatus());
            }
            
            // 会员状态匹配
            if (userQueryRequest.getIsVip() != null) {
                queryWrapper.eq("isVip", userQueryRequest.getIsVip());
            }
        }
        
        List<User> userList = userService.list(queryWrapper);
        List<UserVO> userVOList = userList.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(userVOList);
    }

    /**
     * 分页获取用户列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    @Operation(summary = "分页获取用户列表", description = "分页获取用户列表，支持用户名/手机号模糊匹配和角色状态筛选")
    public ApiResponse<Page<UserVO>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
        long current = 1;
        long size = 10;
        
        if (userQueryRequest != null) {
            current = userQueryRequest.getCurrent();
            size = userQueryRequest.getPageSize();
        }
        
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        
        if (userQueryRequest != null) {
            // 用户名模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getUserName())) {
                queryWrapper.like("userName", userQueryRequest.getUserName());
            }
            
            // 手机号模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getPhone())) {
                queryWrapper.like("phone", userQueryRequest.getPhone());
            }
            
            // 账号模糊匹配
            if (StringUtils.isNotBlank(userQueryRequest.getUserAccount())) {
                queryWrapper.like("userAccount", userQueryRequest.getUserAccount());
            }
            
            // 用户角色精确匹配
            if (userQueryRequest.getUserRole() != null) {
                queryWrapper.eq("userRole", userQueryRequest.getUserRole());
            }
            
            // 用户状态精确匹配
            if (userQueryRequest.getStatus() != null) {
                queryWrapper.eq("status", userQueryRequest.getStatus());
            }
            
            // 会员状态匹配
            if (userQueryRequest.getIsVip() != null) {
                queryWrapper.eq("isVip", userQueryRequest.getIsVip());
            }
        }
        
        Page<User> userPage = userService.page(new Page<>(current, size), queryWrapper);
        
        // 创建新的Page对象用于返回UserVO
        Page<UserVO> userVOPage = new Page<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
        List<UserVO> userVOList = userPage.getRecords().stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }).collect(Collectors.toList());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 获取用户统计信息
     *
     * @return 包含总用户数和会员数的统计信息
     */
    @GetMapping("/count")
    @Operation(summary = "获取用户统计信息", description = "获取系统中总用户数和会员数量")
    public ApiResponse<Map<String, Long>> getUserCount() {
        // 获取总用户数
        long totalUserCount = userService.count();
        
        // 获取会员数量(isVip=1)
        QueryWrapper<User> vipQueryWrapper = new QueryWrapper<>();
        vipQueryWrapper.eq("isVip", 1);
        long vipUserCount = userService.count(vipQueryWrapper);
        
        // 获取正常状态用户数量(status=0)
        QueryWrapper<User> normalStatusWrapper = new QueryWrapper<>();
        normalStatusWrapper.eq("status", 0);
        long normalUserCount = userService.count(normalStatusWrapper);
        
        // 获取封禁状态用户数量(status=1)
        QueryWrapper<User> bannedStatusWrapper = new QueryWrapper<>();
        bannedStatusWrapper.eq("status", 1);
        long bannedUserCount = userService.count(bannedStatusWrapper);
        
        // 构造返回结果
        Map<String, Long> countMap = new HashMap<>();
        countMap.put("totalUserCount", totalUserCount);
        countMap.put("vipUserCount", vipUserCount);
        countMap.put("normalUserCount", normalUserCount);
        countMap.put("bannedUserCount", bannedUserCount);
        
        return ResultUtils.success(countMap);
    }

    /**
     * 激活会员码
     *
     * @param request 会员码激活请求
     * @return 是否激活成功
     */
    @PostMapping("/activate-vip")
    @Operation(summary = "激活会员码", description = "用户使用会员码激活会员服务")
    public ApiResponse<Boolean> activateVipCode(@RequestBody VipCodeActivateRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        if (request.getUserId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (StringUtils.isBlank(request.getCode())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "会员码不能为空");
        }
        
        try {
            boolean result = vipCodeService.activateVipCode(request.getUserId(), request.getCode());
            return ResultUtils.success(result);
        } catch (IllegalArgumentException e) {
            log.error("会员码激活失败：{}", e.getMessage());
            throw new BusinessException(ErrorCode.PARAMS_ERROR, e.getMessage());
        } catch (RuntimeException e) {
            log.error("会员码激活系统错误：{}", e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "会员码激活失败，请稍后重试");
        }
    }

    /**
     * 手机号注册
     *
     * @param userPhoneRegisterRequest 手机号注册请求
     * @return 用户ID
     */
    @PostMapping("/phone/register")
    @Operation(summary = "手机号注册", description = "使用手机号和验证码注册用户")
    public ApiResponse<Long> userPhoneRegister(@RequestBody UserPhoneRegisterRequest userPhoneRegisterRequest) {
        if (userPhoneRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userPhoneRegister(userPhoneRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 手机号登录
     *
     * @param userPhoneLoginRequest 手机号登录请求
     * @param request HTTP请求
     * @return 用户信息
     */
    @PostMapping("/phone/login")
    @Operation(summary = "手机号登录", description = "使用手机号和验证码登录")
    public ApiResponse<UserVO> userPhoneLogin(@RequestBody UserPhoneLoginRequest userPhoneLoginRequest, HttpServletRequest request) {
        if (userPhoneLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userPhoneLogin(userPhoneLoginRequest, request);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return ResultUtils.success(userVO);
    }

    /**
     * 重置密码
     *
     * @param resetPasswordRequest 重置密码请求
     * @return 是否重置成功
     */
    @PostMapping("/reset-password")
    @Operation(summary = "重置密码", description = "使用手机号和验证码重置密码")
    public ApiResponse<Boolean> resetPassword(@RequestBody ResetPasswordRequest resetPasswordRequest) {
        if (resetPasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数不能为空");
        }
        
        String phone = resetPasswordRequest.getPhone();
        String code = resetPasswordRequest.getCode();
        String newPassword = resetPasswordRequest.getNewPassword();
        String confirmPassword = resetPasswordRequest.getConfirmPassword();
        
        // 校验参数
        if (StringUtils.isAnyBlank(phone, code, newPassword, confirmPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        
        // 校验手机号格式
        if (phone.length() != 11) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号格式不正确");
        }
        
        // 校验两次密码是否一致
        if (!newPassword.equals(confirmPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        
        // 密码长度校验
        if (newPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
        }
        
        // 验证短信验证码
        boolean isCodeValid = smsService.verifyCode(phone, code);
        if (!isCodeValid) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误或已过期");
        }
        
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        User user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "未找到该手机号注册的用户");
        }
        
        // 更新密码
        String encryptPassword = userService.encryptPassword(newPassword);
        user.setUserPassword(encryptPassword);
        boolean result = userService.updateById(user);
        
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "密码重置失败，请稍后重试");
        }
        
        ApiResponse<Boolean> response = ResultUtils.success(true);
        response.setMessage("密码重置成功");
        return response;
    }

    /**
     * 检查当前登录用户会员是否过期
     *
     * @param request HTTP请求
     * @return 是否过期，true-已过期，false-未过期
     */
    @GetMapping("/check-vip-expire")
    @Operation(summary = "检查会员是否过期", description = "检查当前登录用户的会员时间是否过期")
    public ApiResponse<Boolean> checkVipExpire(HttpServletRequest request) {
        // 获取当前登录用户
        User user = userService.getLoginUser(request);
        
//        // 检查是否为会员
//        if (user.getIsVip() == null || user.getIsVip() != 1) {
//            // 非会员直接返回已过期
//            return ResultUtils.success(true);
//        }
        
        // 检查会员到期时间
        Date vipExpire = user.getVipExpire();
        if (vipExpire == null) {
            // 会员到期时间为空，视为已过期
            return ResultUtils.success(true);
        }
        
        // 比较当前时间与到期时间
        Date currentTime = new Date();
        boolean isExpired = currentTime.after(vipExpire);
        
        return ResultUtils.success(isExpired);
    }

    /**
     * 根据时间段获取新增用户统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate 结束日期 (格式: yyyy-MM-dd) 
     * @param request HTTP请求
     * @return 新增用户统计数据
     */
    @GetMapping("/statistics/new-users")
    @Operation(summary = "获取新增用户统计", description = "管理员根据时间段获取新增用户统计数据")
    public ApiResponse<UserStatisticsVO> getNewUsersStatistics(
            @RequestParam String startDate,
            @RequestParam String endDate,
            HttpServletRequest request) {
        
        // 验证管理员权限
        ApiResponse<UserStatisticsVO> authResult = userAuthValidator.validateAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (StringUtils.isAnyBlank(startDate, endDate)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始日期和结束日期不能为空");
        }
        
        UserStatisticsVO result = userService.getNewUsersStatistics(startDate, endDate);
        return ResultUtils.success(result);
    }
    
    /**
     * 根据时间段获取新增会员统计
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate 结束日期 (格式: yyyy-MM-dd)
     * @param request HTTP请求
     * @return 新增会员统计数据
     */
    @GetMapping("/statistics/new-vips")
    @Operation(summary = "获取新增会员统计", description = "管理员根据时间段获取新增会员统计数据")
    public ApiResponse<VipStatisticsVO> getNewVipsStatistics(
            @RequestParam String startDate,
            @RequestParam String endDate,
            HttpServletRequest request) {
        
        // 验证管理员权限
        ApiResponse<VipStatisticsVO> authResult = userAuthValidator.validateAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (StringUtils.isAnyBlank(startDate, endDate)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始日期和结束日期不能为空");
        }
        
        VipStatisticsVO result = userService.getNewVipsStatistics(startDate, endDate);
        return ResultUtils.success(result);
    }
    
    /**
     * 根据时间段获取用户注册趋势
     *
     * @param startDate 开始日期 (格式: yyyy-MM-dd)
     * @param endDate 结束日期 (格式: yyyy-MM-dd)
     * @param granularity 时间粒度 (day/week/month)
     * @param request HTTP请求
     * @return 用户注册趋势数据
     */
    @GetMapping("/statistics/registration-trend")
    @Operation(summary = "获取用户注册趋势", description = "管理员根据时间段和粒度获取用户注册趋势")
    public ApiResponse<RegistrationTrendVO> getRegistrationTrend(
            @RequestParam String startDate,
            @RequestParam String endDate,
            @RequestParam(defaultValue = "day") String granularity,
            HttpServletRequest request) {
        
        // 验证管理员权限
        ApiResponse<RegistrationTrendVO> authResult = userAuthValidator.validateAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (StringUtils.isAnyBlank(startDate, endDate)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始日期和结束日期不能为空");
        }
        
        if (!Arrays.asList("day", "week", "month").contains(granularity)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "时间粒度只能是day、week或month");
        }
        
        RegistrationTrendVO result = userService.getRegistrationTrend(startDate, endDate, granularity);
        return ResultUtils.success(result);
    }
    
    /**
     * 获取即将到期的会员列表
     *
     * @param days 提前多少天提醒 (默认7天)
     * @param current 当前页
     * @param pageSize 页大小
     * @param request HTTP请求
     * @return 即将到期的会员列表
     */
    @GetMapping("/statistics/expiring-vips")
    @Operation(summary = "获取即将到期的会员", description = "管理员获取即将到期的会员列表")
    public ApiResponse<Page<UserVO>> getExpiringVips(
            @RequestParam(defaultValue = "7") Integer days,
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long pageSize,
            HttpServletRequest request) {
        
        // 验证管理员权限
        ApiResponse<Page<UserVO>> authResult = userAuthValidator.validateAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        if (days <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "提前天数必须大于0");
        }
        
        Page<UserVO> result = userService.getExpiringVips(days, current, pageSize);
        return ResultUtils.success(result);
    }
    
    /**
     * 获取会员状态分布统计
     *
     * @param request HTTP请求
     * @return 会员状态分布数据
     */
    @GetMapping("/statistics/vip-distribution")
    @Operation(summary = "获取会员状态分布", description = "管理员获取会员状态分布统计")
    public ApiResponse<VipDistributionVO> getVipDistribution(HttpServletRequest request) {
        
        // 验证管理员权限
        ApiResponse<VipDistributionVO> authResult = userAuthValidator.validateAdminAuth(request);
        if (authResult != null) {
            return authResult;
        }
        
        VipDistributionVO result = userService.getVipDistribution();
        return ResultUtils.success(result);
    }
    
    // endregion
} 